import { ResultUtil } from '../common/HandlerRespUtil';
import { PayloadUtil } from '../common/PayloadUtil';
import { Config } from '../sdk/ConfigManager';
import { LingmaSDKTool } from '../sdk/LingmaSDKTool';
import { ActionEnum, HandlePolicy, RawRequest, RequestPreHandler } from '../sdk/RequestHandleSDK';

/**
 * Custom script filter, through which request content can be sent to a remote server for processing (such as code scanning, content audit, etc.)
 */
export const sensitiveContentFilter: RequestPreHandler = {
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  handle: async (request: RawRequest, SDKTool: LingmaSDKTool) => {
    const dataMap = PayloadUtil.getPayloadData(request.payload);
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    for (const [key, value] of dataMap.entries()) {
      if (value.includes('password')) {
        return ResultUtil.buildPreHandlerResponse(HandlePolicy.BLOCK, request.payload, 'Content includes password');
      }
    }
    // If you need to handle different actions differently, refer to the following implementation
    switch (request.action) {
      case ActionEnum.COMPLETION:
        // do something
        break;
      case ActionEnum.CODE_PROBLEM_SOLVE:
        // do something
        break;
      default:
        return ResultUtil.buildPreHandlerResponse(HandlePolicy.NO_OPS, request.payload, 'No processing required');
    }
    return ResultUtil.buildPreHandlerResponse(HandlePolicy.NO_OPS, request.payload, 'No processing required');
  },
};

/**
 * 将自定义脚本过滤器添加到配置中
 * @param config LingmaExtensionSDK提供的统一管理配置的对象
 */
export function modifyConfig(config: Config) {
  config.contentHandlers.push(sensitiveContentFilter);
  return config;
}
